package net.xju3_4.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.xju3_4.common.framework.simplemvc.RequestMapping;
import net.xju3_4.common.utils.JSONUtil;
import net.xju3_4.common.utils.PageInfo;
import net.xju3_4.common.utils.Result;
import net.xju3_4.entity.OrderEntity;
import net.xju3_4.service.RentalService;
import net.xju3_4.service.impl.RentalServiceImpl;

import java.util.HashMap;
import java.util.Map;

/**
 * 租车服务控制器
 * 独立的租车业务控制器，不修改现有OrderController
 */
@RequestMapping("/api/rental")
public class RentalController {

    private RentalService rentalService = new RentalServiceImpl();

    /**
     * 创建租车订单
     */
    @RequestMapping("/create.do")
    public void createRental(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
            
            // 获取请求参数
            String userId = req.getParameter("userId");
            String carId = req.getParameter("carId");
            String startDate = req.getParameter("startDate");
            String endDate = req.getParameter("endDate");
            String dailyRent = req.getParameter("dailyRent");
            
            // 参数验证
            if (userId == null || carId == null || startDate == null || endDate == null) {
                JSONUtil.printByJSON(resp, Result.fail("参数不完整"));
                return;
            }
            
            // 创建租车订单
            Map<String, Object> rentalData = new HashMap<>();
            rentalData.put("userId", userId);
            rentalData.put("carId", carId);
            rentalData.put("startDate", startDate);
            rentalData.put("endDate", endDate);
            rentalData.put("dailyRent", dailyRent);
            
            OrderEntity rental = rentalService.createRental(rentalData);
            
            if (rental != null) {
                JSONUtil.printByJSON(resp, Result.success(rental, "租车订单创建成功"));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("租车订单创建失败"));
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(resp, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    /**
     * 获取用户的租车记录
     */
    @RequestMapping("/userRentals.do")
    public void getUserRentals(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
            
            String userId = req.getParameter("userId");
            String status = req.getParameter("status");
            String pageNumStr = req.getParameter("pageNum");
            String pageSizeStr = req.getParameter("pageSize");
            
            if (userId == null) {
                JSONUtil.printByJSON(resp, Result.fail("用户ID不能为空"));
                return;
            }
            
            int pageNum = pageNumStr == null ? 1 : Integer.parseInt(pageNumStr);
            int pageSize = pageSizeStr == null ? 10 : Integer.parseInt(pageSizeStr);
            
            PageInfo<OrderEntity> pageInfo = rentalService.getUserRentals(userId, status, pageNum, pageSize);
            
            if (pageInfo != null) {
                JSONUtil.printByJSON(resp, Result.success(pageInfo, "查询成功"));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("暂无数据"));
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(resp, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    /**
     * 获取租车订单详情
     */
    @RequestMapping("/detail.do")
    public void getRentalDetail(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
            
            String rentalId = req.getParameter("rentalId");
            String userId = req.getParameter("userId");
            
            if (rentalId == null || userId == null) {
                JSONUtil.printByJSON(resp, Result.fail("参数不完整"));
                return;
            }
            
            OrderEntity rental = rentalService.getRentalDetail(Integer.parseInt(rentalId), userId);
            
            if (rental != null) {
                JSONUtil.printByJSON(resp, Result.success(rental, "查询成功"));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("订单不存在或无权限访问"));
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(resp, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    /**
     * 取消租车订单
     */
    @RequestMapping("/cancel.do")
    public void cancelRental(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");

            String rentalId = req.getParameter("rentalId");
            String userId = req.getParameter("userId");
            String reason = req.getParameter("reason");

            System.out.println("DEBUG: 取消订单请求 - rentalId: " + rentalId + ", userId: " + userId + ", reason: " + reason);

            if (rentalId == null || userId == null) {
                JSONUtil.printByJSON(resp, Result.fail("参数不完整"));
                return;
            }

            // 先获取订单详情，提供更详细的错误信息
            OrderEntity rental = rentalService.getRentalDetail(Integer.parseInt(rentalId), userId);
            if (rental == null) {
                JSONUtil.printByJSON(resp, Result.fail("订单不存在或无权限访问"));
                return;
            }

            boolean success = rentalService.cancelRental(Integer.parseInt(rentalId), userId, reason);

            if (success) {
                JSONUtil.printByJSON(resp, Result.success("订单取消成功"));
            } else {
                String statusDesc = rentalService.getStatusDescription(rental.getStatus());
                JSONUtil.printByJSON(resp, Result.fail("订单取消失败，当前状态：" + statusDesc + "，只有待支付和待取车状态的订单可以取消"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(resp, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    /**
     * 更新租车订单状态
     */
    @RequestMapping("/updateStatus.do")
    public void updateRentalStatus(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
            
            String rentalId = req.getParameter("rentalId");
            String newStatus = req.getParameter("newStatus");
            String userId = req.getParameter("userId");
            
            if (rentalId == null || newStatus == null || userId == null) {
                JSONUtil.printByJSON(resp, Result.fail("参数不完整"));
                return;
            }
            
            boolean success = rentalService.updateRentalStatus(Integer.parseInt(rentalId), Integer.parseInt(newStatus), userId);
            
            if (success) {
                JSONUtil.printByJSON(resp, Result.success("状态更新成功"));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("状态更新失败"));
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(resp, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    /**
     * 计算租车费用
     */
    @RequestMapping("/calculateCost.do")
    public void calculateRentalCost(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
            
            String startDate = req.getParameter("startDate");
            String endDate = req.getParameter("endDate");
            String dailyRentStr = req.getParameter("dailyRent");
            
            if (startDate == null || endDate == null || dailyRentStr == null) {
                JSONUtil.printByJSON(resp, Result.fail("参数不完整"));
                return;
            }
            
            Map<String, Object> costInfo = rentalService.calculateRentalCost(startDate, endDate, Double.parseDouble(dailyRentStr));
            
            JSONUtil.printByJSON(resp, Result.success(costInfo, "费用计算成功"));
            
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(resp, Result.fail("系统错误：" + e.getMessage()));
        }
    }
}
